import 'dart:io';

import 'package:flutter/material.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/ui/home/rank/rank_content_viewmodel.dart';
import 'package:gold/ui/home/rank/rank_history_viewmodel.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/// @description: 排行榜-历史记录
/// @author tangzhentao
/// @created at 11:21 2024/12/29


class RankHistoryPage extends StatelessWidget {
  /// 排行榜类型
  late final ValueNotifier<PoolType> _typeNotifier;
  /// 控制器
  late final PageController _controller;

  RankHistoryPage({super.key, required PoolType type}) {
    _typeNotifier = ValueNotifier(type);
    _controller = PageController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: xfgAppbar(
        title: '排行榜',
        bottom: PreferredSize(
            preferredSize: Size(XfgSize().screenWidth, XfgSize().size44),
            child: Padding(
              padding: EdgeInsets.only(bottom: XfgSize().size10),
              child: Container(
                  height: XfgSize().size34,
                  decoration: BoxDecoration(color: XfgColor.colorF2, borderRadius: BorderRadius.circular(XfgSize().size34)),
                  child: ValueListenableBuilder<PoolType>(
                    valueListenable: _typeNotifier,
                    builder: (_, type, __) => Row(
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [_rankTypeWidget(PoolType.day, type), _rankTypeWidget(PoolType.week, type),_rankTypeWidget(PoolType.month, type),_rankTypeWidget(PoolType.year, type)]
                    ),
                  )
              ),
            )
        ),
      ),
      body: Container(
        margin: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, 0),
        decoration: BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size10)),
        child: PageView(
            controller: _controller,
            onPageChanged: (index) => _typeNotifier.value = _getType(index),
            children: const [
              _RankHistoryListPage(type: PoolType.day),
              _RankHistoryListPage(type: PoolType.week),
              _RankHistoryListPage(type: PoolType.month),
              _RankHistoryListPage(type: PoolType.year),
            ]
        ),
      ),
    );
  }

  /// 获取类型
  PoolType _getType(int index) {
    switch (index) {
      case 0:
        return PoolType.day;
      case 1:
        return PoolType.week;
      case 2:
        return PoolType.month;
      default:
        return PoolType.year;
    }
  }

  /// 排行榜类型通用布局
  Widget _rankTypeWidget(PoolType type, PoolType select) => GestureDetector(
    onTap: () {
      if (type != select) {
        _typeNotifier.value = type;
        _controller.jumpToPage(type.index);
      }
    },
    behavior: HitTestBehavior.opaque,
    child: Container(
      width: XfgSize().size75,
      decoration: select == type ? BoxDecoration(color: XfgColor.theme, borderRadius: BorderRadius.circular(XfgSize().size34)):null,
      alignment: Alignment.center,
      child: XfgText(type.name, fontSize: XfgSize().text16, color: select == type ? XfgColor.white:XfgColor.text1, bold: FontWeight.bold),
    ),
  );
}

/// 排行榜历史记录列表
class _RankHistoryListPage extends StatefulWidget {
  /// 排行类型
  final PoolType type;

  const _RankHistoryListPage({required this.type});

  @override
  State<StatefulWidget> createState() => _RankHistoryListState();
}

class _RankHistoryListState extends State<_RankHistoryListPage> with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<RankHistoryViewmodel>(
        model: RankHistoryViewmodel(widget.type),
        onInit: (data) => data.loadFirst(),
        builder: (ctx, history) => SmartRefresher(
          controller: history.controller,
          enablePullUp: true,
          enablePullDown: true,
          onRefresh: history.refresh,
          onLoading: history.loadMore,
          child: ListView.builder(
              itemCount: history.list.length,
              itemBuilder: (_, index) {
                final data = history.list[index];
                final Widget numberWidget;
                if (index == 0) {
                  numberWidget = Image.asset(Res.imagesRankFirst, width: XfgSize().size18, height: XfgSize().size21);
                } else if (index == 1 || index == 2) {
                  numberWidget = Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(top: XfgSize().size4),
                    decoration: const BoxDecoration(image: DecorationImage(image: AssetImage(Res.imagesRankNumber), fit: BoxFit.fill)),
                    width: XfgSize().size16, height: XfgSize().size20,
                    child: XfgText('${index + 1}', fontSize: XfgSize().text10, color: XfgColor.text1, height: Platform.isIOS ? 1:null),
                  );
                } else {
                  numberWidget = XfgText('${index + 1}', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.w500);
                }
                return Container(
                  height: XfgSize().size72,
                  decoration: BoxDecoration(border: Border(bottom: BorderSide(color: XfgColor.colorE, width: XfgSize().size0_5))),
                  child: Row(
                    children: [
                      Expanded(
                          flex: 3,
                          child: Row(
                            children: [
                              Container(
                                padding: EdgeInsets.only(left: XfgSize().size16),
                                width: XfgSize().size54,
                                alignment: Alignment.centerLeft,
                                child: numberWidget,
                              ),
                              HttpImage(data.member?.avatar, size: Size.square(XfgSize().size40), radius: BorderRadius.circular(XfgSize().size40)),
                              SizedBox(width: XfgSize().size8),
                              XfgText(data.member?.nickname?? '', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold, children: [
                                TextSpan(text: '\n${data.member?.uid?? ''}', style: TextStyle(color: XfgColor.text1, fontWeight: FontWeight.normal))
                              ]),
                            ],
                          )
                      ),
                      Expanded(flex: 1, child: Center(child: XfgText('${data.rate?? 0}%', fontSize: XfgSize().text14, color: XfgColor.text1))),
                      Expanded(
                        flex: 2,
                        child: Center(
                          child: XfgText(data.updatedAt?? '',
                              textAlign: TextAlign.center,
                              fontSize: XfgSize().text14, color: XfgColor.text1,height: widget.type == PoolType.week || widget.type == PoolType.month? 1.5:1),
                        ),
                      )
                    ],
                  ),
                );
              }
          ),
        )
    );
  }

  @override
  bool get wantKeepAlive => true;
}